package com.algorithm.base.backtracking;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 46. 全排列
 *
 * @author Amadeus
 * @date 2023/11/10
 */
public class Permute {

    List<List<Integer>> result = new ArrayList<>();
    Deque<Integer> deque = new LinkedList<>();

    public List<List<Integer>> permute(int[] nums) {
        int[] used = new int[nums.length + 1];
        backtracking(nums, used);
        return result;
    }

    public void backtracking(int[] nums, int[] used) {
        if (deque.size() == nums.length) {
            result.add(new ArrayList<>(deque));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i] == 0) {
                deque.addLast(nums[i]);
                used[i] = 1;
                backtracking(nums, used);
                deque.removeLast();
                used[i] = 0;
            }
        }
    }

}
